package net.oschina.simpleplus.jwt;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import net.oschina.simpleplus.kits.MapKit;
import net.oschina.simpleplus.vo.UserVo;

@Aspect
@Component
public class JwtAspect {
	
	@Autowired private JwtFactory jwtFactory;

	@Pointcut("execution( * net.oschina.simpleplus.ctrl.*Ctrl.*(..))")
	public void aspect(){}
	
	
	@Around("aspect()")
	public Object around(ProceedingJoinPoint pjp) throws Throwable{
		try {
			if(((MethodSignature)pjp.getSignature()).getMethod().isAnnotationPresent(SkipJwtAuth.class)){
				return pjp.proceed();
			}
			HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
			UserVo userFromToken = jwtFactory.getUserFromToken(request.getHeader("token"));
			Object[] args = pjp.getArgs();
			args[0] = userFromToken;
			return pjp.proceed(args);
		} catch (Exception e) {
			return MapKit.buildErrorMap(4000, e.getMessage());
		}
	}
}
